package com.pf.business.upload.listener;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.MapUtils;
import com.google.common.collect.Lists;
import com.pf.business.upload.dto.UploadBill;
import com.pf.common.dto.ExcelErrorParam;
import com.pf.common.enums.ResultRespEnum;
import com.pf.common.exception.BusinessException;
import com.pf.utils.ValidateUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
 * 配合异步处理的监听器，仿照自带的 PageReadListener 监听器
 *
 * @author PanFei
 * @version 1.0.0
 * @createTime 2023/7/16 20:02
 */
@Slf4j
public class AsyncUploadBillReadListener implements ReadListener<UploadBill> {

    public static int BATCH_COUNT = 100;

    private Map<Integer, UploadBill> cachedDataMap = MapUtils.newHashMapWithExpectedSize(BATCH_COUNT);
    private List<UploadBill> billList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private final Consumer<List<UploadBill>> consumer;
    private List<ExcelErrorParam> excelErrorMsgList;

    public AsyncUploadBillReadListener(Consumer<List<UploadBill>> consumer, List<ExcelErrorParam> excelErrorMsgList) {
        this.consumer = consumer;
        this.excelErrorMsgList = excelErrorMsgList;
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        List<String> excelTitleList = Lists.newArrayList();
        // 获取excel的表头名称
        Field[] fields = UploadBill.class.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(ExcelProperty.class)) {
                ExcelProperty excelProperty = field.getDeclaredAnnotation(ExcelProperty.class);
                String[] valueArray = excelProperty.value();
                if (valueArray != null) {
                    excelTitleList.add(valueArray[0]);
                }
            }
        }
        // 校验excel表头
        headMap.forEach((index, readCellData) -> {
            if (!excelTitleList.contains(readCellData.getStringValue())) {
                log.error(">>>>> invokeHead：excel不存在【{}】表头字段信息", readCellData.getStringValue());
                throw new BusinessException(ResultRespEnum.UPLOAD_TEMPLATE_ERROR);
            }
        });
    }

    @Override
    public void invoke(UploadBill uploadBill, AnalysisContext context) {
        Integer rowIndex = context.readRowHolder().getRowIndex();
        cachedDataMap.put(rowIndex + 1, uploadBill);
        if (cachedDataMap.size() >= BATCH_COUNT) {
            cachedDataMap.forEach((rowNum, bill) -> {
                ExcelErrorParam excelErrorParam = ValidateUtils.validateExcelData(rowNum, bill);
                if (excelErrorParam != null) {
                    excelErrorMsgList.add(excelErrorParam);
                } else {
                    billList.add(bill);
                }
            });
            consumer.accept(billList);
            cachedDataMap = MapUtils.newHashMapWithExpectedSize(BATCH_COUNT);
            billList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (cachedDataMap.size() > 0) {
            cachedDataMap.forEach((rowNum, bill) -> {
                ExcelErrorParam excelErrorParam = ValidateUtils.validateExcelData(rowNum, bill);
                if (excelErrorParam != null) {
                    excelErrorMsgList.add(excelErrorParam);
                } else {
                    billList.add(bill);
                }
            });
            consumer.accept(billList);
        }
    }
}
